package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;


    @Override
    public void submit(Orders orders) {

        Long userId = BaseContext.getCurrentId();//用户id
        long id = IdWorker.getId();//订单编号
        BigDecimal total = new BigDecimal(0);//订单总金额

        User user = userService.getById(userId);
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());


        //TODO 2. 向订单详情表中添加多条数据（以购物车数据为准）
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //查询用户的购物车
        List<ShoppingCart> shoppingCartList = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, userId)
                .list();
        for (ShoppingCart cart : shoppingCartList) {
            //创建一个OrderDetail
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);//订单id
            orderDetail.setNumber(cart.getNumber());//设置数量
            orderDetail.setDishFlavor(cart.getDishFlavor());//口味
            orderDetail.setDishId(cart.getDishId());//菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//套餐id
            orderDetail.setName(cart.getName());//名称
            orderDetail.setImage(cart.getImage());//图片
            orderDetail.setAmount(cart.getAmount());//金额 单价

            //先计算小计
            BigDecimal multiply = cart.getAmount().multiply(new BigDecimal(cart.getNumber()));
            total = total.add(multiply);

            //将orderdetail放入list集合中
            orderDetailList.add(orderDetail);
        }

        orderDetailService.saveBatch(orderDetailList);


        //TODO 1. 向订单表中添加一条数据
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setCheckoutTime(LocalDateTime.now());//支付时间
        orders.setStatus(2);//状态 订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(id));//订单编号，采用雪花算法生成
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收获人
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setAmount(total);// 总金额
        orders.setId(id);

        this.save(orders);// 保存


        //清空购物车
        shoppingCartService.lambdaUpdate()
                .eq(ShoppingCart::getUserId, userId)
                .remove();
    }

    @Override
    public Page<OrdersDto> userPage(Integer page, Integer pageSize) {
        Page<OrdersDto> pageInfo = new Page<>(page, pageSize);
        ordersMapper.userPage(pageInfo, BaseContext.getCurrentId());
        return pageInfo;
    }
}
